<template>
  <!-- 选择商品弹窗 -->
  <el-dialog
    title="选择商品"
    :visible.sync="selectProductDialog"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-form ref="productForm" :model="productFilters" class="demo-form-inline">
      <el-form-item label="商品名称" prop="goodsName">
        <div class="product-form-item">
          <el-input
            class="input"
            v-model="productFilters.goodsName"
            placeholder="请输入"
            @keyup.enter.native="handleSearch"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item label="商品编码" prop="goodsCode">
        <div class="product-form-item">
          <el-input
            class="input"
            ref="goodsCodeInput"
            v-model="productFilters.goodsCode"
            placeholder="请输入"
            @keyup.enter.native="handleSearch"
          ></el-input>
          <div class="product-dialog-btns">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm('productForm')">重置</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <el-table
      :data="productList"
      ref="productTable"
      :row-class-name="getRowClass"
      @row-click="handleRowClick"
      @keydown.native="handleKeyDown"
      tabindex="0"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            ref="productTable"
            :data="props.row.goodsSpecList"
            :row-class-name="getChildRowClass"
            @row-click="handleChildRowClick"
            @selection-change="(val) => handleSelectionChange(val, props.row)"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="goodsSpecName" label="商品规格名称" />
            <el-table-column prop="retailPrice" label="零售价格">
            </el-table-column>
            <el-table-column prop="memberMoney" label="会员价格">
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名称" width="120">
      </el-table-column>
      <el-table-column prop="categoryId" label="商品分类">
        <template slot-scope="scope">
          {{ selectCategoryIdLabel(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="商品头图">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="scope.row.goodsPhoto"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goodsCode" label="商品编码"> </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="pageSizes"
      :layout="'total, sizes, prev, pager, next, jumper'"
      @pagination="getList"
    />
    <div slot="footer">
      <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      <el-button @click="close"> 取消 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCategoryListAPI, getGoodsListAPI } from "@/api/system/product";

export default {
  name: "SelectProductDialog",
  props: {
    selectProductList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      selectProductDialog: false,
      productFilters: {
        goodsName: "",
        goodsCode: "",
      },
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 5,
      },
      productList: [],
      options: [],
      allSelectedData: [],
      hoveredRowIndex: -1,
      selectedRows: [],
      selectedChildRows: [],
      expandedRows: [], // 存储展开的行ID
      pageSizes: [5, 10, 15, 25, 35, 55],
    };
  },
  computed: {
    selectCategoryIdLabel() {
      return (id) => {
        const item = this.options.find((item) => item.id === id);
        return item ? item.categoryName : "";
      };
    },
  },
  methods: {
    getRowClass({ row, rowIndex }) {
      const isSelected = this.selectedRows.some((r) => r.id === row.id);
      const isHovered = this.hoveredRowIndex === rowIndex;

      if (isSelected) return "selected-row";
      if (isHovered) return "hovered-row";
      return "";
    },

    getChildRowClass({ row }) {
      return this.selectedChildRows.some((r) => r.id === row.id)
        ? "selected-row"
        : "";
    },
    subErrKeys() {
      this.$refs.productTable.$el.focus();
    },
    handleKeyDown(event) {
      const key = event.key;
      const maxIndex = this.productList.length - 1;
      this.$refs.goodsCodeInput.blur();
      this.$refs.productTable.$el.focus();
      if (key === "ArrowUp") {
        this.hoveredRowIndex = Math.max(0, this.hoveredRowIndex - 1);
        this.scrollToRow(this.hoveredRowIndex);
        event.preventDefault();
      } else if (key === "ArrowDown") {
        this.hoveredRowIndex = Math.min(maxIndex, this.hoveredRowIndex + 1);
        this.scrollToRow(this.hoveredRowIndex);
        event.preventDefault();
      } else if (key === "Enter") {
        if (this.hoveredRowIndex !== -1) {
          const row = this.productList[this.hoveredRowIndex];
          this.toggleRowSelection(row);

          const selectedItems = row.goodsSpecList || [];
          const parentRow = row;

          // 先过滤掉之前来自同一父级的选中项
          this.allSelectedData = this.allSelectedData.filter(
            (item) => item.parentId !== parentRow.id
          );

          // 给每个选中项添加父级的属性
          const newSelectedItems = selectedItems.map((item) => ({
            ...item,
            ...parentRow,
            retailPrice: item.retailPrice,
            memberMoney: item.memberMoney,
          }));

          // 合并新的选中项，过滤掉已存在的项
          const uniqueSelectedItems = newSelectedItems.filter(
            (newItem) =>
              !this.allSelectedData.some(
                (existItem) => existItem.id === newItem.id
              )
          );

          this.allSelectedData = [
            ...this.allSelectedData,
            ...uniqueSelectedItems,
          ];
          this.handleConfirm();
          console.log("所有选中的数据: ", this.allSelectedData);
        }
      } else if (key === " ") {
        if (this.hoveredRowIndex !== -1) {
          this.toggleRowSelection(this.productList[this.hoveredRowIndex]);
        }
        event.preventDefault();
      }
    },

    toggleRowSelection(row) {
      const index = this.selectedRows.findIndex((r) => r.id === row.id);
      if (index === -1) {
        this.selectedRows.push(row);
      } else {
        this.selectedRows.splice(index, 1);
      }
    },

    toggleChildRowSelection(row, forceSelect = false) {
      const index = this.selectedChildRows.findIndex((r) => r.id === row.id);
      if (index === -1) {
        this.selectedChildRows.push(row);
      } else if (!forceSelect) {
        this.selectedChildRows.splice(index, 1);
      }
    },

    handleRowClick(row) {
      console.log("row: ", row);
      this.hoveredRowIndex = this.productList.indexOf(row);
      this.toggleRowSelection(row);

      // 选中所有子项
      if (row.goodsSpecList && row.goodsSpecList.length > 0) {
        row.goodsSpecList.forEach((child) => {
          this.toggleChildRowSelection(child, true);
        });

        // 更新allSelectedData
        this.handleSelectionChange(row.goodsSpecList, row);
      }

      // 切换展开状态
      const index = this.expandedRows.indexOf(row.id);
      if (index === -1) {
        this.expandedRows.push(row.id);
      } else {
        this.expandedRows.splice(index, 1);
      }
    },

    handleChildRowClick(row) {
      this.toggleChildRowSelection(row);
    },

    scrollToRow(index) {
      this.$nextTick(() => {
        const table = this.$refs.table;
        if (table && table.bodyWrapper) {
          const rows = table.bodyWrapper.querySelectorAll(".el-table__row");
          if (rows[index]) {
            rows[index].scrollIntoView({
              behavior: "smooth",
              block: "nearest",
            });
          }
        }
      });
    },
    handleSelectionChange(selectedItems, parentRow) {
      console.log("selectedItems, parentRow: ", selectedItems, parentRow);
      if (selectedItems.length > 0) {
        // 先过滤掉之前来自同一父级的选中项
        this.allSelectedData = this.allSelectedData.filter(
          (item) => item.parentId !== parentRow.id
        );
        // 给每个选中项添加父级的
        const newSelectedItems = selectedItems.map((item) => ({
          ...item,
          ...parentRow,
          retailPrice: item.retailPrice,
          memberMoney: item.memberMoney,
        }));
        // 合并新的选中项，过滤掉已存在的项
        const uniqueSelectedItems = newSelectedItems.filter(
          (newItem) =>
            !this.allSelectedData.some(
              (existItem) => existItem.id === newItem.id
            )
        );
        this.allSelectedData = [
          ...this.allSelectedData,
          ...uniqueSelectedItems,
        ];
      } else {
        // 获取当前展开行的所有子项
        const currentItems = parentRow.goodsSpecList;
        // 找出当前取消的项
        const removedItems = currentItems.filter(
          (item) => !selectedItems.some((selected) => selected.id === item.id)
        );
        // 移除取消的项
        this.allSelectedData = this.allSelectedData.filter(
          (item) => !removedItems.some((removed) => removed.id === item.id)
        );
      }
      console.log("所有选中的数据: ", this.allSelectedData);
    },
    getCateList() {
      getCategoryListAPI({ pageNum: 1, pageSize: 999999 }).then((response) => {
        this.options = response.rows;
      });
    },
    openSelectProduct() {
      // 清空所有选中数据
      this.allSelectedData = [];
      this.selectedRows = [];
      this.selectedChildRows = [];
      this.hoveredRowIndex = -1;
      this.selectProductDialog = true;
      // this.getList();
      this.productList = [];
      this.total = 0;
      this.getCateList();

      // 清空所有子表格的选中状态
      setTimeout(() => {
        if (this.$refs.productTable) {
          const expandedRows = this.$refs.productTable.store.states.expandRows;
          expandedRows.forEach((row) => {
            const childTable = row.$refs.productTable;
            if (childTable) {
              childTable.clearSelection();
            }
          });
        }
        // this.$refs.productTable.$el.blur();
        this.$refs.goodsCodeInput.focus();
      }, 300);
    },
    getList() {
      getGoodsListAPI({ ...this.productFilters, ...this.queryParams }).then(
        (res) => {
          if (res.code == 200) {
            console.log(res, "返回数据");
            res.rows.forEach((item) => {
              item.goodsSpecList = JSON.parse(item.goodsSpec);
            });
            this.productList = res.rows;
            this.total = res.total;
            setTimeout(() => {
              if (this.$refs.productTable) {
                this.$refs.productTable.$el.focus();
              }
            }, 300);
          }
        }
      );
    },
    close() {
      this.selectProductDialog = false;
      this.resetForm("productForm");
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleSearch() {
      console.log(this.productFilters, "开始查询");
      this.getList();
    },
    handleConfirm() {
      console.log(this.allSelectedData, "选择的商品");

      // 过滤掉已存在的商品
      const filteredData = this.allSelectedData.filter(
        (item) =>
          !this.selectProductList.some((existItem) => existItem.id === item.id)
      );

      // 更新选中数据，只保留未重复的
      this.allSelectedData = filteredData;

      // 清除重复项的选中状态和背景色
      this.selectedRows = this.selectedRows.filter(
        (row) => !this.selectProductList.some((item) => item.id === row.id)
      );
      this.selectedChildRows = this.selectedChildRows.filter(
        (row) => !this.selectProductList.some((item) => item.id === row.id)
      );

      if (this.allSelectedData.length === 0) {
        // this.$message.warning("请至少选择一件商品");
        return;
      }
      this.$emit("handle-select", this.allSelectedData);
    },
    handleRemoved() {
      // 获取所有展开行的子表格实例
      const expandedRows = this.$refs.productTable.store.states.expandRows;
      expandedRows.forEach((row) => {
        const childTable = row.$refs.productTable;
        if (childTable) {
          childTable.clearSelection();
        }
      });
      this.allSelectedData = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.product-form-item {
  display: flex;

  .input {
    width: 60%;
  }

  .product-dialog-btns {
    flex: 1;
    margin-left: 20px;
  }
}
::v-deep .el-table {
  .selected-row {
    background-color: rgb(24, 144, 255, 0.3) !important;
    // color: #fff;
  }
  .hovered-row {
    background-color: rgb(166, 215, 39, 0.3) !important;
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background-color: rgb(24, 144, 255, 0.3) !important;
    // color: #fff;
  }
}
</style>
